﻿using System;
using DBProvider;
using DBProvider.Providers;
using System.IO;
using Brettle.Web.NeatUpload;
using System.Linq;
using System.Collections.Generic;

namespace HealthCommunity.Controls
{
	public partial class UCVideoEdit : System.Web.UI.UserControl
	{
		private IVideoProvider _videoProvider;
		private List<DrugStore> lstDrugStore;

		private Video CurrentVideo;

		public string ServerURL
		{
			get
			{
				if(Request.Url.Port > 0)
				{
					return string.Format("http://{0}:{1}", Request.Url.Host, Request.Url.Port.ToString());
				}
				else
				{
					return "http://" + Request.Url.Host;
				}
			}
		}

		public int CurrentVideoID
		{
			get
			{
				var id = CommonHelper.QueryStringInt("videoid");

				if(id <= 0)
				{
					if(ViewState["videoid"] != null)
					{
						id = (int)ViewState["videoid"];
					}
				}

				return id;
			}
			set
			{
				ViewState["videoid"] = value;
			}
		}

		protected void Page_Load(object sender, EventArgs e)
		{
			if(!IsPostBack)
			{
				BindVideoCategory();
				BindDrugStore();
			}
		}

		protected void Page_PreRender(object sender, EventArgs e)
		{
			BindVideo();
		}

		protected void btnRemove_Click(object sender, EventArgs e)
		{
			if(lstMemberSelected.SelectedItem != null)
			{
				lstMemberSelected.Items.Remove(lstMemberSelected.SelectedItem);
			}
		}

		protected void btnAdd_Click(object sender, EventArgs e)
		{
			if(lstMember.SelectedItem != null)
			{
				var item = new System.Web.UI.WebControls.ListItem(lstMember.SelectedItem.Text, lstMember.SelectedItem.Value);

				if(!lstMemberSelected.Items.Contains(item))
				{
					lstMemberSelected.Items.Add(item);
				}
			}
		}

		protected void ddlDrugStore_SelectedIndexChanged(object sender, EventArgs e)
		{
			BindMember();
		}

		private void BindVideoCategory()
		{
			var videoProvider = new VideoProvider();

			var videoCategories = videoProvider.GetAllVideoCategory();

			ddlVideoCategory.Items.Clear();
			ddlVideoCategory.DataSource = videoCategories;
			ddlVideoCategory.DataBind();
		}

		private void BindVideo()
		{
			if(CurrentVideoID > 0)
			{
				if(_videoProvider == null)
				{
					_videoProvider = new VideoProvider();
				}

				if(CurrentVideo == null)
				{
					CurrentVideo = _videoProvider.GetVideo(CurrentVideoID);
				}

				if(CurrentVideo != null)
				{
					this.txtVideoAddress.Text = CurrentVideo.VideoAddress;
					this.txtVideoDescription.Text = CurrentVideo.VideoDescription;
					this.txtVideoTitle.Text = CurrentVideo.VideoTitle;
					this.imgVideoFront.Visible = true;
					this.imgVideoFront.ImageUrl = "~/ImageHandler.ashx?picturesize=140&videoid=" + CurrentVideo.VideoID.ToString();
					this.chbIsPublic.Checked = (CurrentVideo.IsPublic == 1);
					this.chbCanComment.Checked = (CurrentVideo.VideoCanComment == 1);
					if(ddlVideoCategory.Items != null && ddlVideoCategory.Items.Count > 0)
					{
						foreach(System.Web.UI.WebControls.ListItem item in ddlVideoCategory.Items)
						{
							item.Selected = (item.Value.Equals(CurrentVideo.VideoCategoryID.ToString()));
						}
					}

					if(CurrentVideo.IsPublic != 1)
					{
						var videoAndShareTo = _videoProvider.GetVideoAndShareToByVideo(CurrentVideoID);

						if(videoAndShareTo != null && videoAndShareTo.Count > 0)
						{
							var videoAndShareToDrugStore = videoAndShareTo.Where(vs => vs.ShareToDrugStoreID > 0);
							var videoAndShareToMember = videoAndShareTo.Where(vs => vs.ShareToMemberID > 0);

							if(videoAndShareToDrugStore != null)
							{
								var lstVideoShareToDrugStore = videoAndShareToDrugStore.ToList();

								if(lstVideoShareToDrugStore.Count > 0)
								{
									foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
									{
										var drugStoreID = int.Parse(item.Value);

										item.Selected = lstVideoShareToDrugStore.Count(vs => vs.ShareToDrugStoreID == drugStoreID) > 0;
									}
								}
							}

							lstMemberSelected.Items.Clear();

							if(videoAndShareToMember != null)
							{
								var lstVideoShareToMember = videoAndShareToMember.ToList();

								if(lstVideoShareToMember.Count > 0)
								{
									var data = from vs in lstVideoShareToMember
														 select new { UserCName = vs.User.UserCName, ShareToMemberID = vs.ShareToMemberID };

									foreach(var dataItem in data)
									{
										var item = new System.Web.UI.WebControls.ListItem(dataItem.UserCName, dataItem.ShareToMemberID.ToString());

										//if (!lstMemberSelected.Items.Contains(item))
										//{
										lstMemberSelected.Items.Add(item);
										//}
									}
								}
							}
						}
					}
				}
			}
			else
			{
				this.imgVideoFront.Visible = false;
			}
		}

		private void BindDrugStore()
		{
			chblstDrugStore.Items.Clear();
			chblstDrugStore.DataSource = GetDrugStore();
			chblstDrugStore.DataBind();

			ddlDrugStore.Items.Clear();
			ddlDrugStore.DataSource = GetDrugStore();
			ddlDrugStore.DataBind();

			BindMember();
		}

		private void BindMember()
		{
			if(!string.IsNullOrWhiteSpace(ddlDrugStore.SelectedValue))
			{
				var selectedDrugStoreID = int.Parse(ddlDrugStore.SelectedValue);

				var userProvider = new UserProvider();

				lstMember.DataSource = userProvider.GetUserByDrugStore(selectedDrugStoreID, true);
				lstMember.DataBind();
			}
		}

		private List<DrugStore> GetDrugStore()
		{
			List<DrugStore> result;

			if(this.lstDrugStore != null)
			{
				result = lstDrugStore;
			}
			else
			{
				var drugStoreProvider = new DrugStoreProvider();

				lstDrugStore = drugStoreProvider.GetAllDrugStore();

				result = lstDrugStore;
			}

			return result;
		}

		protected void btnSave_Click(object sender, EventArgs e)
		{
			var theVideo = new Video();
			if(_videoProvider == null)
			{
				_videoProvider = new VideoProvider();
			}

			if(CurrentVideoID > 0)
			{
				theVideo = _videoProvider.GetVideo(CurrentVideoID);
			}

			theVideo.VideoTitle = txtVideoTitle.Text.Trim();
			theVideo.VideoDescription = txtVideoDescription.Text.Trim();
			theVideo.VideoAddress = txtVideoAddress.Text.Trim();
			theVideo.VideoCanComment = (chbCanComment.Checked ? 1 : 0);
			theVideo.VideoUserID = (SiteContext.Current.CurrentUser != null ? SiteContext.Current.CurrentUser.UserID : 0);
			theVideo.DrugStoreID = (SiteContext.Current.CurrentUser != null ? SiteContext.Current.CurrentUser.DrugStoreID : 0);
			theVideo.VideoState = 1;
			theVideo.VideoCategoryID = int.Parse(ddlVideoCategory.SelectedValue);
			theVideo.IsPublic = (chbIsPublic.Checked ? 1 : 0);
			if(fuVideoFront.HasFile)
			{
				string[] imgFileType = { ".jpg", ".jpeg", ".gif", ".png", ".bmp" };
				var theFileExt = Path.GetExtension(fuVideoFront.FileName);
				if(imgFileType.Contains(theFileExt))
				{
					theVideo.VideoFront = fuVideoFront.FileBytes;
				}
			}

			var msg = string.Empty;

			if(CurrentVideoID <= 0)
			{
				theVideo.VideoAddDate = DateTime.Now;

				if(iLocalFile.HasFile)
				{
					if(Path.GetExtension(iLocalFile.FileName).Equals(".flv"))
					{
						var fileName = Guid.NewGuid().ToString() + Path.GetExtension(iLocalFile.FileName);
						theVideo.VideoAddress = ServerURL + "/Videos/" + fileName;
						iLocalFile.MoveTo(Server.MapPath("~/Videos/") + fileName, MoveToOptions.Overwrite);
					}
				}

				CurrentVideo = _videoProvider.CreateVideo(theVideo, out msg);
				if(CurrentVideo != null)
				{
					this.CurrentVideoID = CurrentVideo.VideoID;

					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_VideoAndShareTo> lstNewVideoAndShareTo = new List<RLT_VideoAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltVideoAndShareTo = new RLT_VideoAndShareTo() { VideoID = CurrentVideoID, ShareToDrugStoreID = id };
								lstNewVideoAndShareTo.Add(rltVideoAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltVideoAndShareTo = new RLT_VideoAndShareTo() { VideoID = CurrentVideoID, ShareToMemberID = memberID };
								lstNewVideoAndShareTo.Add(rltVideoAndShareTo);
							}
						}

						if(lstNewVideoAndShareTo.Count > 0)
						{
							_videoProvider.CreateVideoAndShareTo(lstNewVideoAndShareTo);
						}
					}

					ltrMsg.Text = "保存成功";
				}
				else
				{
					ltrMsg.Text = "保存失败了: " + msg;
				}
			}
			else
			{
				if(iLocalFile.HasFile)
				{
					if(string.IsNullOrEmpty(theVideo.VideoAddress))
					{
						var fileName = Guid.NewGuid().ToString() + Path.GetExtension(iLocalFile.FileName);
						theVideo.VideoAddress = ServerURL + "/Videos/" + fileName;
						iLocalFile.MoveTo(Server.MapPath("~/Videos/") + fileName, MoveToOptions.Overwrite);
					}
					else
					{
						var fileName = Path.GetFileName(theVideo.VideoAddress);

						iLocalFile.MoveTo(Server.MapPath("~/Videos/") + fileName, MoveToOptions.Overwrite);
					}
				}

				if(_videoProvider.UpdateVideo(theVideo))
				{
					if(!chbIsPublic.Checked)
					{
						List<int> lstSelectedDrugStoreIDs = new List<int>();
						foreach(System.Web.UI.WebControls.ListItem item in chblstDrugStore.Items)
						{
							if(item.Selected)
							{
								lstSelectedDrugStoreIDs.Add(int.Parse(item.Value));
							}
						}

						List<RLT_VideoAndShareTo> lstVideoAndShareTo = new List<RLT_VideoAndShareTo>();

						if(lstSelectedDrugStoreIDs.Count > 0)
						{
							foreach(var id in lstSelectedDrugStoreIDs)
							{
								var rltVideoAndShareTo = new RLT_VideoAndShareTo() { VideoID = CurrentVideoID, ShareToDrugStoreID = id };
								lstVideoAndShareTo.Add(rltVideoAndShareTo);
							}
						}

						if(lstMemberSelected.Items.Count > 0)
						{
							foreach(System.Web.UI.WebControls.ListItem item in lstMemberSelected.Items)
							{
								var memberID = int.Parse(item.Value);
								var rltVideoAndShareTo = new RLT_VideoAndShareTo() { VideoID = CurrentVideoID, ShareToMemberID = memberID };
								lstVideoAndShareTo.Add(rltVideoAndShareTo);
							}
						}

						_videoProvider.SaveVideoAndShareTo(CurrentVideoID, lstVideoAndShareTo);
					}

					ltrMsg.Text = "保存成功";
				}
				else
				{
					ltrMsg.Text = "保存失败了";
				}
			}
		}
	}
}